import { getUserInfoAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  routes: []
}

const mutations = {
  saveRoutes(state, payload) {
    state.routes = payload
  },
  saveToken(state, payload) {
    state.token = payload
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  }

}

const actions = {
  async loginAction({ commit }, payload) {
    const res = await loginAPI(payload)

    Message.success('登录成功')
    setToken(res.data)
    commit('saveToken', res.data)
    router.push('/')
  },
  async saveUserInfoAction({ commit }) {
    const res = await getUserInfoAPI()
    commit('saveUserInfo', res.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

